package com.github.dwade.shiro.web.login.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.dwade.shiro.web.entity.User;

@Controller
public class LoginController {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@RequestMapping("/")
	public String root(){
		if(SecurityUtils.getSubject().isAuthenticated()){
			return "redirect:/index";
		}
		return "redirect:/login";
	}
	
	@RequestMapping("/index")
	public String index(){
		return "index";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(){
		Session session = SecurityUtils.getSubject().getSession();
		Object obj = session.getId();
		if(SecurityUtils.getSubject().isAuthenticated()){
			return "redirect:/index";
		}
		return "login";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public @ResponseBody Object login(User user, HttpServletRequest request, HttpServletResponse response){
		Subject subject = SecurityUtils.getSubject();
		AuthenticationToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
		try {
			subject.login(token);
			return "/index";
		} catch (AuthenticationException e) {
			logger.error(e.getMessage(), e);
			return "/login";
		}
	}
	
	@RequestMapping(value ="/logout", method = RequestMethod.GET)
	public String logout(){
		SecurityUtils.getSubject().logout();
		return "redirect:/login";
	}
	
}
